package com.helloworld.service;

import com.helloworld.mapper.UserMapper;
import com.helloworld.pojo.User;
import com.helloworld.vo.User.UserAddReq;
import com.helloworld.vo.User.UserInfo;
import com.helloworld.vo.User.UserUpdateReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Integer  addUser(UserAddReq req){
        User user = User.builder()
                .name(req.getName())
                .password(req.getPassword())
                .build();
        userMapper.addUser(user);
        return user.getId();
    }

    public void updateUser(UserUpdateReq req) {
        User user = User.builder()
                .id(req.getId())
                .name(req.getName())
                .password(req.getPassword())
                .build();
        userMapper.updateUser(user);
    }

    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

    public UserInfo queryUserById(Integer  id){
        User user = userMapper.queryUserById(id);
        if(null == user){
            // throw new RuntimeException("user cannot be found by id=" + id);
            return null;
        }
        return UserInfo.builder()
                .id(user.getId())
                .name(user.getName())
                .build();
    }

    public List<UserInfo> queryUserList(String nameLike) {
        List<User> users = userMapper.queryUserList(nameLike);
        if(CollectionUtils.isEmpty(users)){
            return new ArrayList<>();
        }
        return users.stream().map(user -> {
            return UserInfo.builder()
                    .id(user.getId())
                    .name(user.getName())
                    .build();
        }).collect(Collectors.toList());
    }


}
